package book;
import User.AdminUser;
import constant.constant;
import utils.AnalyzingBook;
import utils.ScannerSingleton;

import java.lang.reflect.Array;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.Arrays;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 殇
 * Date: 2025-07-17
 * Time: 12:42
 */
public class Libary {
    private Book[] books;   //书籍数组
    private int bookCount;  //书的实际数量
    Scanner scanner;

    private AnalyzingBook analyzingBook=new AnalyzingBook();  //书籍处理工具
    public Libary() {
        loadAllBook();
        scanner= ScannerSingleton.getScanner();
    }

    public int getBookCount() {
        return bookCount;
    }

    //从文件中读数据
    private void loadAllBook(){
        //将文件的数据读入到allBook临时数组中
        Book[] allBook=analyzingBook.loadObject(constant.ALL_BOOK_FILE_NAME);
        //书籍数组分配默认大小空间
        this.books=new Book[constant.DEFAULT_CAPACITY];
        if(allBook==null)
            bookCount=0;
        else{
            int allBookLen= allBook.length;
            //如果读入的数据数量>当前书的数量，重新分配大小
            if(allBookLen>books.length)
                this.books=new Book[allBookLen];
            //更新书籍
            for(int i=0;i<allBookLen;i++)
                this.books[i]=allBook[i];
            //更新当前书籍数量
            bookCount= allBookLen;
        }
    }

    //上架书籍，即将books数组写入到文件中  =》工具类的storeObject方法
    private void storeBook(){
        analyzingBook.storeObject(books,constant.ALL_BOOK_FILE_NAME);
    }


    //-------------------------------管理员相关操作----------------------------------
    //添加书籍
    public void addBook(Book book){
        if(books.length==bookCount) {
            System.out.println("图书馆的书籍已经满了，无法存放书籍");
            books=Arrays.copyOf(books,2*bookCount);
        }
        if(bookCount==0){
            book.setBookId(1);
        }
        else{
            book.setBookId(books[bookCount-1].getBookId()+1);
        }

        books[bookCount++]=book;

        storeBook();
        System.out.println("书籍"+book.getTitle()+"上架成功！！！");
    }

    //查看库存状态: 显示所有书籍的状态，借出or在存
    public void checkInventoryStatus() {
        loadAllBook();
        for(int i=0;i<bookCount;i++){
            String status=(books[i].isBorrowed()==true)?"已经借出":"正在馆中";
            System.out.println("书籍:"+books[i].getTitle()+status);
        }
    }


    //判断bookId是否合法
    public Book searchBookId(int bookId){
        loadAllBook();
        for(int i=0;i<bookCount;i++){
            if(bookId==books[i].getBookId())
                return books[i];
        }
        return null;
    }

    //根据bookId返回其在books数组中的index
    public int getBooksIndex(int bookId){
        loadAllBook();
        for(int i=0;i<bookCount;i++){
            if(bookId==books[i].getBookId())
                return i;
        }
        return -1;
    }
    //更新书籍
    public void updateBook(Book book) {

        //获取书籍在books中的下标
        int index=getBooksIndex(book.getBookId());
        books[index]=book;

        //books数组内容改变，重新将整个数组存入到文件
        storeBook();
    }

    //删除书籍
    public void removeBook(int bookId){
        loadAllBook();
        //获取删除书籍的index
        int index = getBooksIndex(bookId);
        //覆盖书籍
        for(int i=index;i<bookCount-1;i++){
            books[i]=books[i+1];
        }
        books[bookCount-1]=null;
        //书籍删除，数量减1
        bookCount--;
        //写回文件
        storeBook();
    }


    //查看每本图书的借阅次数
    public void borrowCount(){
        loadAllBook();;
        for(int i=0;i<bookCount;i++){
            System.out.println("书籍"+books[i].getTitle()+"的借阅次数为"+books[i].getBorrowCount());
        }
    }

    //删除上架时间超过1年的书籍
    public void checkAndRemoveOldBooks(){
        loadAllBook();
        //获取时间戳
        long currentTime=System.currentTimeMillis();
        //转为LocalDate
        LocalDate localDate= Instant.ofEpochMilli(currentTime).atZone(ZoneId.systemDefault()).toLocalDate();
        boolean flag=false;
        for(int i=0;i<bookCount;i++){
            //获取书籍的上架时间
            LocalDate tmp=books[i].getShelfDate();
            //计算时间差值
            long yearBetween= ChronoUnit.YEARS.between(localDate,tmp);

            //删除书籍
            if(yearBetween>=1){
                System.out.println("书籍"+books[i].getTitle()+"已经上架超过1年，是否删除？(Y/N)");
                scanner.nextLine();
                char ch=scanner.nextLine().charAt(0);
                if(ch!='N'&&ch!='n')
                    removeBook(books[i].getBookId());
                i--;   //由于删除书籍后，后面书籍往前覆盖，因此删除后，i位置仍需要判断，因此i--，循环后i++，继续判断i位置
                flag=true;
            }
        }
        if(flag==false)
            System.out.println("没有上架超过1年的书籍，删除失败");
    }

    //查找最受欢迎的前k本书
    public void generateBook(int k) {
        loadAllBook();
        //临时数组存放排序结果
        Book[] tmpBooks=new Book[bookCount];
        for(int i=0;i<bookCount;i++){
            tmpBooks[i]=books[i];
        }
        Arrays.sort(tmpBooks);
        //取前k本书
        for(int i=0;i<k;i++){
            System.out.println(tmpBooks[i].toString());
        }
    }


    //----------------------------------普通用户相关操作------------------------------------
    //借阅图书
    public void borrowBook(int bookId) {
        loadAllBook();
        for(int i=0;i<bookCount;i++){
            //找到借阅书籍
            if(books[i].getBookId()==bookId){
                books[i].setBorrowed(true);
                books[i].incrementBorrowCount();
                break;
            }
        }
        storeBook();
    }
    //归还图书
    public void returnBook(int bookId) {
        loadAllBook();
        for(int i=0;i<bookCount;i++) {
            //找到借阅书籍
            if (books[i].getBookId() == bookId) {
                books[i].setBorrowed(false);
                books[i].decreaseBorrowCount();
            }
        }
        storeBook();
    }


    //------------------------------------共用方法----------------------------------------
    //查找书籍
    public void searchBook(){
        System.out.println("请输入查找的书籍名:");
        String bookName=scanner.next();
        Book book=null;
        for(int i=0;i<bookCount;i++){
            if(books[i].getTitle().compareTo(bookName)==0){
                book=books[i];
                break;
            }
        }
        System.out.println(book);
    }
    //打印书籍
    public void display(){
        for(int i=0;i<bookCount;i++){
            System.out.println(books[i]);
        }
    }

    //退出系统
    public void exit(){
        System.out.println("系统已退出！！！");
        System.exit(0);
    }
}